package com.star.uc.infras.aspect;

import com.star.common.core.context.ThreadContext;
import com.star.common.core.contract.constant.ContextConstants;
import com.star.common.kit.ip.Ip2RegionUtil;
import com.star.common.kit.ip.IpUtil;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * 获取ip切面，code
 *
 * @author zhouhengzhe
 * @version 1.0
 * @date 2023/10/27 18:01
 */
@Slf4j
@Aspect
@Component
public class UserAspect {

    @Pointcut("execution(* com.star.uc.api..*.*(..))")
    private void userAspect() {
    }

    @Before("userAspect()")
    public void userAspect(JoinPoint joinPoint) {
        // 接收到请求，记录请求内容
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request  = attributes.getRequest();
        //获取IP
        String ipAddr = IpUtil.toIpAddr(request);
        //获取ip对应的地区
        String area = Ip2RegionUtil.ip2country(ipAddr);
        log.info("ip为：【{}】，国家为：【{}】，省份为：{}", ipAddr, area,Ip2RegionUtil.ip2region(ipAddr));
        ThreadContext.set(ContextConstants.IP,ipAddr);
        ThreadContext.set(ContextConstants.AREA_CODE,area);
    }
}
